from django.shortcuts import render
import rest_framework.serializers as serializers
from rest_framework.views import APIView
import serializer06.models as models
from django.shortcuts import  HttpResponse
import json
from serializer06.serializers import *


class GroupView(APIView):
    def get(self,request,*args,**kwargs):

        group_id=kwargs.get('xxx')
        group_obj=models.UserGroup.objects.get(id=group_id)
        res=UserGroupSerializer(instance=group_obj,many=False) #instance接受queryset对象或者单个model对象，当有多条数据时候，使用many=True,单个对象many=False
        return HttpResponse(json.dumps(res.data,ensure_ascii=False))

    def post(self,request,*args,**kwargs):
        ret = CheckGroupData(data=request.data)  # 这里配置了全局json解析器,使用request.data直接获取数据
        if ret.is_valid():
            print(ret.validated_data)
            # 获取某个字段数据ret.validated_data.get('name')
            return HttpResponse('数据验证成功')
        else:
            print(ret.errors)
            return HttpResponse('数据验证失败')




class RoleView(APIView):
    """角色"""
    def get(self,request,*args,**kwargs):
        roles=models.Role.objects.all()
        res=RolesSerializer(instance=roles,many=True) #instance接受queryset对象或者单个model对象，当有多条数据时候，使用many=True,单个对象many=False
        return HttpResponse(json.dumps(res.data,ensure_ascii=False))


class UserinfoView(APIView):
    """用户信息：多对多"""
    def get(self,request,*args,**kwargs):
        users=models.UserInfo.objects.all()
        # res=UserinfoSerializer(instance=users,many=True) #instance接受queryset对象或者单个model对象，当有多条数据时候，使用many=True,单个对象many=False
        res = UserinfoSerializer_Many2Many(instance=users,many=True)  # instance接受queryset对象或者单个model对象，当有多条数据时候，使用many=True,单个对象many=False
        return HttpResponse(json.dumps(res.data,ensure_ascii=False))


class UserinfoView_Custom(APIView):
    """用户信息：自定义显示"""
    def get(self,request,*args,**kwargs):
        users=models.UserInfo.objects.all()
        # res=UserinfoSerializer(instance=users,many=True) #instance接受queryset对象或者单个model对象，当有多条数据时候，使用many=True,单个对象many=False
        res = UserinfoSerializer_Custom(instance=users,many=True)  # instance接受queryset对象或者单个model对象，当有多条数据时候，使用many=True,单个对象many=False
        return HttpResponse(json.dumps(res.data,ensure_ascii=False))

class UserinfoView_Depth(APIView):
    """用户信息：深度控制"""
    def get(self,request,*args,**kwargs):
        users=models.UserInfo.objects.all()
        # res=UserinfoSerializer(instance=users,many=True) #instance接受queryset对象或者单个model对象，当有多条数据时候，使用many=True,单个对象many=False
        res = UserinfoSerializer_Depth(instance=users,many=True)  # instance接受queryset对象或者单个model对象，当有多条数据时候，使用many=True,单个对象many=False
        return HttpResponse(json.dumps(res.data,ensure_ascii=False))


class UserinfoView_Hyper(APIView):
    """组别信息：深度控制"""
    def get(self,request,*args,**kwargs):
        users=models.UserInfo.objects.all()
        res=UserinfoSerializer_Hyper(instance=users,many=True,context={'request': request})
        #若需生成超链接字段，则需要加context={'request': request}
        return HttpResponse(json.dumps(res.data,ensure_ascii=False))




###############
##数据校验
###############
#自定义验证规则
class MyValidation(object):
    def __init__(self,base):
        self.base = base

    def __call__(self, value): #value是字段值，默认传递
        if value == 'ok':
            message = "关键字%s不能是%s"%(self.base,value)
            raise serializers.ValidationError(message)

##常规验证
class CheckGroupData(serializers.Serializer):
    id=serializers.IntegerField(error_messages={'required':'id不能为空'})
    name=serializers.CharField(error_messages={'required':'组名不能为空'})
    nickname = serializers.CharField(validators=[MyValidation(base='nickname'), ])

##回调验证，钩子验证
##validate_fieldname
# is_valid-->self.run_validation-->to_internal_value-->to_internal_value-->validate_字段名称(执行字段验证,钩子方法)-->validate_method(钩子验证方法)
class MySerializer(serializers.Serializer):
    name = serializers.CharField()

    def validate_name(self,value): # 验证的字段值
        if value.startswith("w"):
            raise serializers.ValidationError('name字段不能以w开头')
        else:
            return value #注意通过验证，必须返回其值